﻿using RSSReader.WebClient.Framework;
using RSSReader.WebClient.Models;
using RSSReader.WebClient.WCFWebRoleService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using WebMatrix.WebData;

namespace RSSReader.WebClient.Controllers
{
  public class AuthenticationController : Controller
  {
    public string GetShaHash(string textToHash)
    {
      var a = new SHA256Managed();
      return Convert.ToBase64String(a.ComputeHash(new System.Text.UTF8Encoding().GetBytes(textToHash)));
    }

    private bool LoginAndCookie(string userId, string password)
    {
      if (WebSecurity.Login(userId, this.GetShaHash(password)))
      {
        DataDistributorClient client = new DataDistributorClient();
        var User = client.GetUser(userId, this.GetShaHash(password));
        var ticket = new FormsAuthenticationTicket(0,
                                                  userId,
                                                  DateTime.UtcNow,
                                                  DateTime.UtcNow.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                                                  false,
                                                  new JavaScriptSerializer().Serialize(new RssReaderTicketUserData { UserId = User.Id, Mail = User.Email }),
                                                  FormsAuthentication.FormsCookiePath);

        var authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
        {
          Domain = FormsAuthentication.CookieDomain,
          Path = FormsAuthentication.FormsCookiePath,
          HttpOnly = true,
          Secure = FormsAuthentication.RequireSSL
        };

        Response.Cookies.Add(authenticationCookie);
        return true;
      }

      return false;
    }

    [HttpGet]
    public ActionResult Login()
    {
      return View();
    }

    [HttpPost]
    public ActionResult Login(UserAuthModel Model)
    {
      string UserName = Model.UserCreation == null ? Model.UserLogin.UserName : Model.UserCreation.UserName;
      string Password = Model.UserCreation == null ? Model.UserLogin.Password : Model.UserCreation.Password;

      if (ModelState.IsValid)
      {
        bool Error = false;

        if (Model.UserCreation != null)
        {
          DataDistributorClient client = new DataDistributorClient();
          var User = client.CreateUser(UserName, this.GetShaHash(Password), Model.UserCreation.Email);
          if (string.IsNullOrEmpty(User.Id))
          {
            Error = true;
          }
        }

        if (!Error && this.LoginAndCookie(UserName, Password))
          return RedirectToAction("Index", "Home");

        if (Error)
          ModelState.AddModelError("UserCreation.UserName", "L'utilisateur existe déjà");
        else
          ModelState.AddModelError("UserLogin", "Utilisateur ou mot de passe incorrect");
      }

      return View(Model);
    }

    public ActionResult Logout()
    {
      WebSecurity.Logout();
      return RedirectToAction("Login");
    }


  }
}